<?php
namespace app\common\model;

use think\facade\Cache;
use hema\wechat\Driver as Wechat;

/**
 * 公众号模型
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'setting';
    protected $createTime = false;

    // 追加字段
    protected $append = [];

    /**
     * 设置项描述
     */
    private $describe = [
        'web' => '站点设置',
        'wxweb' => '网站应用',
        'wxpayisp' => '微信支付服务商设置',
        'webpay' => '支付设置',
        'wxpay' => '微信支付',
        'webtplmsg' => '站点模板消息',
        'subscribe' => '关注回复',//公众号
        'menus' => '公众号菜单',
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem(string $key, $applet_id = null)
    {
        $data = self::getAll($applet_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail(string $key,$applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        // 筛选条件
        $filter = [];
        $filter['key'] = $key;
        $filter['applet_id'] = $applet_id;
        return self::withoutGlobalScope()->where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($applet_id = null)
    {
        $self = new static;
        is_null($applet_id) && $applet_id = $self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        // 筛选条件
        $filter = [];
        $filter['applet_id'] = $applet_id;
        if (!$data = Cache::get('setting_' . $applet_id)) {
            $data = array_column($self::withoutGlobalScope()->where($filter)->select()->toArray(), null, 'key');
            Cache::set('setting_' . $applet_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit(string $key, array $values, $applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        empty($applet_id) && $applet_id = 0;
        //公众号菜单
        if($key == 'menus'){
            $wx = new Wechat;
            $result = $wx->creatMenu($values,$applet_id);
            if($result['errcode'] != 0){
                $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
                return false;
            }
        }
        //关注公众号回复
        if($key == 'subscribe'){
            $values = $this->subscribe($values);
        }
        $model = self::detail($key,$applet_id) ?: $this;
        // 删除系统设置缓存
        Cache::delete('setting_' . $applet_id);
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'applet_id' => $applet_id,
        ]) !== false;
    }

    /**
     * 关注回复内容
     */
    private function subscribe($data)
    {
        if($data['type'] == 'text'){
            $data['content']['media_id'] = ''; 
            $data['content']['title'] = '';
            $data['content']['url'] = '';
            $data['content']['hurl'] = '';
            $data['content']['picurl'] = '';
        }else{
            if(!$material = Material::mediaId($data['content']['media_id'])){
                $this->error = '素材不存在';
                return false; 
            }
            //图片消息
            if($data['type'] == 'image' OR $data['type'] == 'voice'){
                $data['content']['description'] = ''; 
                $data['content']['title'] = '';
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //视频消息
            if($data['type'] == 'video'){
                //获取视频素材内容
                $data['content']['title'] = $material['name'];
                $data['content']['description'] = $material['introduction'];
                $data['content']['url'] = '';
                $data['content']['hurl'] = '';
                $data['content']['picurl'] = '';
            }
            //图文消息
            if($data['type'] == 'news'){
                //获取视频素材内容
                $data['content']['picurl'] = $material['url'];
                $data['content']['url'] = $data['content']['url'] ? $data['content']['url'] : base_url();
                $data['content']['hurl'] = '';
            }
        }
        return $data;
    }

    /**
     * 默认配置
     */
    public function defaultData()
    {
        return [
            'web' => [
                'key' => 'web',
                'describe' => '站点设置',
                'values' => [
                    'name' => '河马云店',//网站名称
                    'domain' => '', //网站域名
                    'icp' => '',    //备案号
                    'address' => '',//地址
                    'keywords' => '',   //关键字
                    'description' => '',    //描述
                    'company' => '',//公司名称
                    'phone' => '',//联系电话
                    'open_id' => '',    //管理员微信ID
                    'wxmap' => '',  //微信地图KEY
                    'copyright' => '©河马云店'  //小程序显示版权
                ],
            ],
            'wxweb' => [
                'key' => 'wxweb',
                'describe' => '网站应用',
                'values' => [
                    'app_id' => '', //公众号APPID
                    'app_secret' => '', //密钥
                ],
            ],
            'wxpayisp' => [
                'key' => 'wxpayisp',
                'describe' => '微信支付服务商设置',
                'values' => [
                    'app_id' => '', //公众号APPID
                    'mch_id' => '',  //商户号
                    'api_key' => '', //密钥
                    'api_v3_key' => '',   //APIv3密钥
                    'cert_id' => '',
                    'cert_pem' => '',
                    'key_pem' => ''
                ],
            ],
            'webpay' => [
                'key' => 'webpay',
                'describe' => '支付设置',
                'values' => [
                    'divide' => [ //交易分佣
                        'mode' => 'unify',//抽取模式unify=统一模式，order=订单类型,
                        'extract' => '0',//统一抽取比例0-30，单位百分，0为不抽取
                        'order' => [
                            'tang' => '0',//堂食抽取比例
                            'waimai' => '0',//外卖抽取比例
                            'ziqu' => '0',//自取订单抽取比例
                        ],
                        'is_delivery' => '0',//包含配送费
                        'agent_fee' => '0',//抽取分账总额的百分比，0-100，0为不抽取，100抽取全部。
                    ],
                    'cost' => [
                        'cash_mode' => 'fixed',//用户提现手续费模式 fixed=固定 ratio=比例 
                        'cash_fee' => 0,//手续费数值
                        'applet_fee' => 0,//小程序审核费0不收取
                    ],
                    'wx' => [
                        'name' => '',//商户全称
                        'app_id' => '', //微信应用
                        'mch_id' => '',//商户号
                        'api_key' => '',//密钥
                        'is_sub' => 0,
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '', //apiclient_key.pem 密钥
                    ]
                ]
            ],
            'wxpay' => [
                'key' => 'wxpay',
                'describe' => '微信支付',
                'values' => [
                    'app_id' => '', //微信应用
                    'is_sub' => 0, //是否为特约商户
                    'mch_id' => '',//商户号
                    'api_key' => '',//密钥
                    'cert_pem' => '', //apiclient_cert.pem 证书
                    'key_pem' => '' //apiclient_key.pem 密钥
                ]
            ],
            'webtplmsg' => [
                'key' => 'webtplmsg',
                'describe' => '模板消息',
                'values' => [
                    'new_order' => '',    //新订单通知
                    'examine' => '',  //审核状态通知
                    'balance' => '',  //账户资金变动提醒
                    'apply' => '',    //申请受理通知
                    'deduction' => '',    //扣费失败通知
                    'testing' => '',  //试用申请成功通知
                    'refund' => '',   //退款发起通知
                    'grab' => '',   //骑手抢单通知
                ],
            ],
            'menus' => [
                'key' => 'menus',
                'describe' => '公众号菜单',
                'values' => [
                /*  0 => [
                        "type" => "view",
                        "name" => "一级菜单",
                        "sub_button" => [
                            0 => [
                                "type" => "click",
                                "name" => "二级菜单",
                                "key" => "关键字"
                            ],
                        ],
                        "url" => base_url()
                    ]*/
                ],
            ],
            'subscribe' => [
                'key' => 'subscribe',
                'describe' => '关注回复',
                'values' => [
                    'is_open' => 1,     //是否开启 0=关闭，1=开启
                    'type' => 'text',   //消息类型 text=文字消息,image=图片消息,news=图文消息,voice=声音消息
                    'content' => [
                        'media_id' => '',//素材
                        'title' => '',//标题
                        'description' => '谢谢关注',//描述或回复内容
                        'url' => '',//链接网址
                        'hurl' => '',//音乐缩略图
                        'picurl' => ''//图片网络地址
                    ]
                ]
            ],
        ];
    }

}
